/**
 * @author ning
 */
var contentTop;
window.addEvent("domready", function(){
    $$("#chatbutton img").addEvent("click", function(){
        contentTop = $("intro").offsetTop;
        $("intro").dispose();
        $("trafficexchange").dispose();
        startNewChat()
    });
    var a = $$("#feedback h2");
    if (location.hash == "#feedback") {
        $("feedback").addClass("expanded");
        $("feedbackmessage").focus()
    }
    else {
        $("feedback").addClass("collapsed")
    }
    a.addEvent("click", function(){
        if ($("feedback").hasClass("expanded")) {
            $("feedback").removeClass("expanded");
            $("feedback").addClass("collapsed")
        }
        else {
            $("feedback").removeClass("collapsed");
            $("feedback").addClass("expanded")
        }
    });
    startUserCounter()
});
function setFavicon(a){
    $$("link[rel=icon]").dispose();
    var b = new Element("link");
    b.rel = "icon";
    b.type = "image/png";
    b.href = a;
    $$("head")[0].grab(b)
}

function killHeaders(a){
    delete a.headers["X-Requested-With"];
    delete a.headers["X-Request"];
    return a
}

function startUserCounter(){
    var d = new Element("div", {
        id: "onlinecount"
    });
    $("header").grab(d);
    function b(){
        setTimeout(a, 120000)
    }
    function c(e){
        d.set("text", e + " users online");
        b()
    }
    function a(){
        killHeaders(new Request({
            url: "/count?rand=" + Math.random(),
            method: "get",
            onSuccess: c,
            onFailure: b
        })).send()
    }
    a()
}

function startNewChat(){
    var u = new Element("div", {
        "class": "chatbox"
    });
    var n = new Element("div", {
        "class": "logwrapper",
        styles: {
            top: contentTop + "px"
        }
    });
    var B = new Element("div", {
        "class": "logbox"
    });
    n.grab(B);
    u.grab(n);
    var r = new Element("div", {
        "class": "controlwrapper"
    });
    var h = new Element("table", {
        "class": "controltable",
        cellpadding: "0",
        cellspacing: "0",
        border: "0"
    });
    var s = new Element("tbody");
    var m = new Element("tr");
    var w = new Element("td", {
        "class": "disconnectbtncell"
    });
    var t = new Element("div", {
        "class": "disconnectbtnwrapper"
    });
    var y = new Element("input", {
        value: "Disconnect",
        "class": "disconnectbtn",
        type: "button",
        disabled: true
    });
    y.set("value", "Disconnect");
    t.grab(y);
    w.grab(t);
    m.grab(w);
    var i = new Element("td", {
        "class": "chatmsgcell"
    });
    var c = new Element("div", {
        "class": "chatmsgwrapper"
    });
    var l = new Element("textarea", {
        "class": "chatmsg",
        cols: "80",
        rows: "3",
        disabled: true
    });
    c.grab(l);
    i.grab(c);
    m.grab(i);
    var z = new Element("td", {
        "class": "sendbthcell"
    });
    var v = new Element("div", {
        "class": "sendbtnwrapper"
    });
    var x = new Element("input", {
        "class": "sendbtn",
        type: "button",
        disabled: true
    });
    x.set("value", "Send");
    v.grab(x);
    z.grab(v);
    m.grab(z);
    s.grab(m);
    h.grab(s);
    r.grab(h);
    u.grab(r);
    $(document.body).grab(u);
    var q;
    var e = false;
    var b = false;
    function o(){
        if (b) {
            return
        }
        b = true;
        var G = [["___Omegle___", "/static/favicon.png"], ["\xAF\xAF\xAFOmegle\xAF\xAF\xAF", "/static/altfavicon.png"]];
        var H;
        function F(){
            var J = G.pop();
            document.title = J[0];
            setFavicon(J[1]);
            G.unshift(J);
            H = setTimeout(F, 500)
        }
        F();
        function I(){
            clearTimeout(H);
            b = false;
            document.title = "Omegle";
            setFavicon("/static/favicon.png");
            $(document).removeEvent("mousemove", I);
            $(document).removeEvent("keydown", I);
            $(document).removeEvent("focus", I);
            $(window).removeEvent("mousemove", I);
            $(window).removeEvent("keydown", I);
            $(window).removeEvent("focus", I)
        }
        $(document).addEvent("mousemove", I);
        $(document).addEvent("keydown", I);
        $(document).addEvent("focus", I);
        $(window).addEvent("mousemove", I);
        $(window).addEvent("keydown", I);
        $(window).addEvent("focus", I)
    }
    function g(){
        return B.scrollTop >= B.scrollHeight - B.clientHeight
    }
    function j(){
        B.scrollTop = B.scrollHeight
    }
    function C(G){
        var H = new Element("div", {
            "class": "logitem"
        });
        H.grab(G);
        var F = g();
        B.grab(H);
        if (F) {
            j()
        }
    }
    function d(F){
        var G = new Element("div", {
            "class": "statuslog"
        });
        G.appendText(F);
        C(G);
        o()
    }
    function a(J, K){
        if (J == "you") {
            var H = "youmsg";
            var I = "You:"
        }
        else {
            var H = "strangermsg";
            var I = "Stranger:";
            o()
        }
        var L = new Element("div", {
            "class": H
        });
        var G = new Element("span", {
            "class": "msgsource"
        });
        G.appendText(I);
        L.grab(G);
        L.appendText(" ");
        var F = true;
        $each(K.split("\n"), function(M){
            if (!F) {
                L.grab(new Element("br"))
            }
            F = false;
            L.appendText(M)
        });
        C(L);
        if (J == "stranger" && (K.indexOf("FBI") !== -1 || K.toLowerCase().indexOf("federal bureau") !== -1)) {
            d("If the above message says you have been reported to the FBI, it is not legitimate. Please ignore it.")
        }
    }
    function p(){
        l.set("disabled", true);
        x.set("disabled", true);
        y.set("disabled", true);
        $(window).removeEvent("beforeunload", k);
        $(window).removeEvent("unload", A);
        e = true;
        var I = new Element("div");
        var H = new Element("input");
        H.type = "submit";
        H.value = "Start a new conversation";
        H.addEvent("click", function(){
            u.dispose();
            startNewChat()
        });
        I.grab(H);
        I.appendText(" or ");
        var G = new Element("a");
        G.set("text", "save this log");
        G.set("href", "#");
        var L = B.get("html");
        var F = new Date();
        var K = F.getFullYear() + "-";
        if (F.getMonth() < 9) {
            K += "0"
        }
        K += (F.getMonth() + 1) + "-";
        if (F.getDate() < 10) {
            K += "0"
        }
        K += F.getDate();
        G.addEvent("click", function(O){
            O.preventDefault();
            var N = new Element("form");
            N.set("method", "post");
            N.set("action", "/downloadlog");
            N.setStyle("display", "none");
            var M = new Element("input");
            M.set("type", "hidden");
            M.set("name", "date");
            M.set("value", K);
            N.grab(M);
            var P = new Element("input");
            P.set("type", "hidden");
            P.set("name", "log");
            P.set("value", L);
            N.grab(P);
            $(document.body).grab(N);
            N.submit()
        });
        I.grab(G);
        I.appendText(" or ");
        var J = new Element("a");
        J.href = "/feedback";
        J.appendText("send us feedback");
        I.grab(J);
        I.appendText(".");
        C(I)
    }
    function onGetNotification(F){
        $each(F, function(G){
            switch (G[0]) {
                case "":
                    d("Looking for someone you can chat with. Hang on.");
                    break;
                case "keep":
                    d("You're now chatting with a random stranger. Say hi!");
                    l.set("disabled", false);
                    x.set("disabled", false);
                    l.focus();
                    break;
                case "gotMessage":
                    var H = G[1];
                    a("stranger", H);
                    break;
                case "strangerDisconnected":
                    d("Your conversational partner has disconnected.");
                    p();
                    break
            }
        })
    }
    function getNotification(F){
        if (F == undefined) {
            F = 0
        }
        if (F > 2) {
            d("Connection asploded.");
            p()
        }
        if (e) {
            return
        }
        killHeaders(new Request.JSON({
            url: "/getNotification",
            onSuccess: function(G){
                if (e) {
                    return
                }
                if (G == null) {
                    d("Connection imploded.");
                    p()
                }
                else {
                    onGetNotification(G);
                    getNotification()
                }
            },
            onFailure: function(){
                getNotification(F + 1)
            }
        })).post({
            id: q
        })
    }
    function f(){
        l.focus();
        var F = l.value;
        if (!F) {
            return
        }
        l.value = "";
        a("you", F);
        killHeaders(new Request({
            url: "/send",
            data: {
                msg: F,
                id: q
            }
        })).send()
    }
    function A(){
        if (e) {
            return
        }
        killHeaders(new Request({
            url: "/disconnect",
            data: {
                id: q
            }
        })).send();
        d("You have disconnected.");
        p()
    }
    function k(F){
        F.preventDefault();
        F.event.returnValue = "Leaving this page will end your conversation."
    }
    x.addEvent("click", f);
    y.addEvent("click", function(){
        if (confirm("Are you sure you want to disconnect?")) {
            A()
        }
    });
    l.addEvent("keypress", function(F){
        if (F.code == 13 && !(F.shift || F.alt || F.meta)) {
            f();
            F.preventDefault()
        }
    });
    d("Connecting to server...");
    killHeaders(new Request.JSON({
        url: "/start",
        onSuccess: function(F){
            y.set("disabled", false);
            $(window).addEvent("beforeunload", k);
            $(window).addEvent("unload", A);
            q = F;
            getNotification()
        },
        onFailure: function(){
            d("Error connecting to server. Please try again.");
            p()
        }
    })).post()
};
